package com.cindata

import com.cindata.dictionary.EvaluateDict
import com.cindata.dictionary.ExecStatusDict
import com.cindata.dictionary.ImportFileTypeDict
import grails.gorm.transactions.Transactional
import net.sf.json.JSON
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.formula.functions.T
import org.grails.plugins.excelimport.AbstractExcelImporter
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

@Secured(['isAuthenticated()'])
@Transactional
class ContactImportBatchController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def evaluateService

    def sessionFactory
    def springSecurityService

    def index(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        def order = params["order"]
        def sort = params["sort"]
        String sql = " from ContactImportBatch e where 1=1"
        String sql1 = " from ContactImport e where 1=1"
        def user = User.findById(springSecurityService.principal.id)
        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += " and e.createBy.account.id in ${accountSql}"
            sql1 += " and e.createBy.account.id in ${accountSql}"
        }
        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.createdDate desc "
        }
        def estateImportBatchList = ContactImportBatch.executeQuery(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def estateImportList = ContactImportBatch.executeQuery(sql1, [max: params.max ?: 10, offset: params.offset ?: 0])
        respond EstateImportBatch, model: [estateImportList: estateImportList, estateImportBatchList: estateImportBatchList, estateImportBatchCount: EstateImportBatch.count()]
    }

    def show(EstateImportBatch estateImportBatch)
    {
        respond estateImportBatch
    }

    @Transactional
    def ajaxSearch()
    {
        def batchs = params["batchs"]
        def result = false
        def sql = "from ContactImportBatch e where 1=1 "
        def user = User.findById(springSecurityService.principal.id)
        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += " and e.createBy.account.id in ${accountSql}"
        }
        if (batchs)
        {
            sql += " and e.batchNumber = '${batchs}' "
        }
        def batchList = EstateImportBatch.executeQuery(sql).asList()
        if (batchList.size() != 0)
        {
            result = true
        }
        else
        {
            result = false
        }
        render([result: result] as JSON)
    }

    @Transactional
    def searchEstate()
    {
        def order = params["order"]
        def sort = params["sort"]
        def batchs = params["batchs"]
        //批次号
        def createBy = params["createBy"]
        //导入经手人
        def status = params['status']
        //导入状态
        def evaluateType = params['evaluateType']
        //处理方式
        def startDate = params["startDate"]
        //开始时间
        def endDate = params["endDate"]
        //结束时间
        def importFileType = params["importFileType"]
        def sqlParam = [:]
        //导入文件类型
        String sql = "from ContactImportBatch e where 1=1"
        def user = User.findById(springSecurityService.principal.id)
        def accountSql = Account.FilterAccountSql(user)
        if (accountSql)
        {
            sql += " and e.createBy.account.id in ${accountSql}"
        }
        if (batchs)
        {
            sql += " and e.batchNumber like '%${batchs}%'"
        }
        if (status)
        {
            sql += " and e.status.name = '${status}'"
        }
        if (evaluateType)
        {
            sql += " and e.evaluateType.id= '${evaluateType}'"
        }
        if (startDate && endDate)
        {
            //中文日期转换
            sqlParam.startDate = DateUtil.GetDateBeginByDateStr(startDate.toString())
            sqlParam.endDate = DateUtil.GetNextDateBeginByDateStr(endDate.toString())
            sql += "and e.createdDate >= :startDate and e.createdDate  < :endDate "
        }
        if (createBy)
        {
            sql += "and e.createBy.id = '${createBy}'"
        }
        if (importFileType)
        {
            sql += "and e.importFileType.id = '${importFileType}'"
        }

        //查询总数
        String countSql = "select count(e.id) " + sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += "order by e.createdDate desc "
        }
        println(sql)
        //执行查询方法
        def estateImportBatchList = EstateImportBatch.executeQuery(sql, sqlParam, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = EstateImportBatch.executeQuery(countSql, sqlParam)
        if (estateImportBatchList != null)
        {

            respond EstateImportBatch, model: [estateImportBatchList: estateImportBatchList, estateImportBatchCount: count[0], params: params], view: 'index'
        }
        else
        {
            respond EstateImportBatch, view: 'index'
        }
        // println(estateImportList.get(0))
        //        println(estateImportList.get(0).getCreateBy().username)
    }

    def create()
    {
        respond new EstateImportBatch(params)
    }

    @Transactional
    def csvImport()
    {
        /**
         * 读取文件*/
        def file = request.getFile('myFile')
        def fileCharset = FileUtil.GetFileCharset(file.getInputStream())

        //将文件传给对应类,读取文件
        def importer = new ContactCSVImporter()
        def estateMapList = importer.read(file.getInputStream(), fileCharset)

        //获取集合
        def estateNum = estateMapList.size()

        def batch = params["batch"]

        def createBy = User.findByUsername(sec.loggedInUserInfo(field: "username"))
        def currentDate = new Date()

        /**
         * 加入批次信息*/
        Map param = [batchNumber: batch,
            count: estateNum,
            dealCount: 0,
            status: ExecStatusDict.EXECUTING(),
            createBy: createBy,
            isDeleted: 0]

        def newImportBatch = new ContactImportBatch(param)

        newImportBatch.save flush:true

        //将批次信息加入批次表中
        if (newImportBatch.hasErrors())
        {
            println "EstateImportBatch not saved, errors = ${newImportBatch.errors}"
            respond ContactImportBatch, model: ["message": "导入失败", "success": false], view: "message"
        }

        println '批次ID: [' + newImportBatch?.id + "]"

        /**
         * 遍历存入excel里的数据*/

       // evaluateService.batchInserts(estateMapList, newImportBatch, currentDate)
        evaluateService.contactInserts(estateMapList, newImportBatch, currentDate)

        respond EstateImportBatch, model: ["success": true, "key": newImportBatch.id], view: "message"
        return
    }

    def getProgress(Long progressKey)
    {
        def progress = evaluateService.getProgress(progressKey)
        render([progress: progress] as grails.converters.JSON)
    }

    @Transactional
    def save(EstateImportBatch estateImportBatch)
    {
        if (estateImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estateImportBatch.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estateImportBatch.errors, view: 'create'
            return
        }

        estateImportBatch.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'estateImportBatch.label', default: 'EstateImportBatch'), estateImportBatch.id])
                redirect estateImportBatch
            }
            '*' { respond estateImportBatch, [status: CREATED] }
        }
    }

    def exportFailureContact(Long id)
    {
        //根据批次ID导出失败数据
        def batch = ContactImportBatch.findById(id)
        String sql = "from ContactImport where batch.id = " + batch.id + " and evaluateStatue.name = '失败'"
        println(sql)
        def result = ContactImport.executeQuery(sql)
        println(result)
        //导出数据
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("处理失败押品", "UTF-8") + ".xls")
        response.contentType = "application/x-rarx-rar-compressed"
        ExcelExportService excelExportService = new ExcelExportService()
        //提前还款情况报表
        String[] headers = ["借款人编号", "借款人姓名", "性别", "证件类型", "证件号码", "手机号",
            "住址", "银联借记卡号", "户口所在地", "工作单位", "职务","失败原因"]
        String[] params = ["externalId", "fullName", "sex", "identityType", "idNumber", "cellphone",
            "address", "bankAccountNo", "householdAddress", "workUnitName", "position",'reason']
        List<Map<String, T>> listn = new ArrayList<Map<String, T>>();
        result.each {
            print(it.evaluateStatue.name)
            Map<String, T> m = new HashMap<String, T>();
            m.put("externalId", it?.externalId)
            m.put("fullName", it?.fullName)
            m.put("sex", it?.sex)
            m.put("identityType", it?.identityType?.name)
            m.put("idNumber", it?.idNumber)
            m.put("cellphone", it?.cellphone)

            m.put("address", it?.address)
            m.put("bankAccountNo", it?.bankAccountNo)
            m.put("householdAddress", it?.householdAddress)
            m.put("workUnitName", it?.workUnitName)
            m.put("position", it?.position)
            m.put("reason",it?.reason)

            listn.add(m)
        }
        HSSFWorkbook workbook = excelExportService.exportExcel("导入失败借款人", headers, listn, params);
        workbook.write(response.getOutputStream());
        response.flushBuffer() //立即清空输出
        response.getOutputStream().close();
        println("下载完成")
    }

    def edit(EstateImportBatch estateImportBatch)
    {
        respond estateImportBatch
    }

    @Transactional
    def update(EstateImportBatch estateImportBatch)
    {
        if (estateImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (estateImportBatch.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond estateImportBatch.errors, view: 'edit'
            return
        }

        estateImportBatch.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'estateImportBatch.label', default: 'EstateImportBatch'), estateImportBatch.id])
                redirect estateImportBatch
            }
            '*' { respond estateImportBatch, [status: OK] }
        }
    }

    @Transactional
    def delete(EstateImportBatch estateImportBatch)
    {

        if (estateImportBatch == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        estateImportBatch.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'estateImportBatch.label', default: 'EstateImportBatch'), estateImportBatch.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'estateImportBatch.label', default: 'EstateImportBatch'), params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    // 失败押品转人工
    @Transactional
    def evaluateFailureEstate(Long id)
    {
        evaluateService.evaluateFailureEstate(id)

        def estateImportBatch = EstateImportBatch.findById(id)
        estateImportBatch.evaluateType = EvaluateDict.AUTOANDARTIFICIAL()
        estateImportBatch.save flush: true

        redirect action: 'index'
    }
}
